/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tstudy.laoshibang.weike;

import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.custom.SoundView;
import com.tstudy.laoshibang.custom.SoundView.OnVolumeChangedListener;
import com.tstudy.laoshibang.login.RegistSuccessFragment;
import com.tstudy.laoshibang.utils.LogUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue.IdleHandler;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import de.greenrobot.event.EventBus;


public class MediaPlayerFullScreen extends Activity implements
        OnBufferingUpdateListener, OnCompletionListener,
        OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {

    private static final String TAG = "MediaPlayerDemo";
    private int mVideoWidth;
    private int mVideoHeight;
    private MediaPlayer mMediaPlayer;
    private boolean     mIsPrepared;
    private SurfaceView mVideoView;
    private RelativeLayout mProgressLayout;
    private int mDuration;
    private SurfaceHolder holder;
    private String path;
    private Bundle extras;
    private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;
    
    private View controlView = null;
	private PopupWindow controlerPop = null;
	private TextView durationTextView = null;
	private int         mCurrentBufferPercentage;
	private TextView playedTextView = null;
	private SeekBar seekBar = null;  
	private int mProgress;
	private int mScale = 30*1000;
	private int mPlayedTime;
	private ImageButton fullScreen = null;
	private ImageButton backward = null;
	private ImageButton start = null;
	private ImageButton forward = null;
	private ImageButton sound = null;
	private GestureDetector mGestureDetector = null;
	private AudioManager mAudioManager = null;  
	
	private SoundView mSoundView = null;
	private PopupWindow mSoundWindow = null;
	
	private View extralView = null;
//	private PopupWindow extralWindow = null;
	
	private static int screenWidth = 0;
	private static int screenHeight = 0;
	private static int controlHeight = 0;  

	private int maxVolume = 0;
	private int currentVolume = 0;  
	private final static int TIME = 6868;  
	private boolean isControllerShow = true;
	private boolean isPaused = false;
	private boolean isFullScreen = false;
	private boolean isSilent = false;
	private boolean isSoundShow = false;
	private boolean isOnline = false; 
	private boolean isChangedVideo = false;
	private boolean mStartWhenPrepared;
    private int   mSeekWhenPrepared;
    
    public static void show(Activity activity,int position,String url){
    	Intent intent = new Intent(activity, MediaPlayerFullScreen.class);
    	intent.putExtra(CONSTANT.ARGS.POSITION, position);
    	intent.putExtra(CONSTANT.ARGS.URL,url);
    	activity.startActivity(intent);
    }
	
    /**
     * 
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        LogUtil.d("------onCreate==" + this);
        setContentView(R.layout.mediaplayer_demo);
        mVideoView = (SurfaceView) findViewById(R.id.surface);
        mProgressLayout = (RelativeLayout) findViewById(R.id.media_play_demo_progress);
        mProgressLayout.setVisibility(View.VISIBLE);
        myHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if(controlerPop != null && mVideoView.isShown()){
					controlerPop.showAtLocation(mVideoView, Gravity.BOTTOM, 0, 0);
					controlerPop.update(screenWidth, controlHeight);
				}
			}
		}, CONSTANT.LOAD_DATA_DELAY_TIME);
        controlView = getLayoutInflater().inflate(R.layout.controler, null);
        controlerPop = new PopupWindow(controlView);
        fullScreen = (ImageButton) controlView.findViewById(R.id.fullscreen);
        backward = (ImageButton) controlView.findViewById(R.id.backward);
        start = (ImageButton) controlView.findViewById(R.id.start);
        forward = (ImageButton) controlView.findViewById(R.id.forward);
        sound = (ImageButton) controlView.findViewById(R.id.sound);
        durationTextView = (TextView) controlView.findViewById(R.id.duration);
        playedTextView = (TextView) controlView.findViewById(R.id.has_played);
        fullScreen.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				EventBus.getDefault().post(new Integer(getCurrentPosition()));
				stopPlayback();
				finish();
			}
        });
        backward.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				seekTo(Math.max(0,getCurrentPosition() - mScale));
			}
        });
        forward.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				seekTo(Math.min(mDuration,getCurrentPosition() + mScale));
			}
        	
        });
        
        start.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				cancelDelayHide();
				if(isPaused){
					start();
					start.setImageResource(R.drawable.player_pause);
					hideControllerDelay();
				}else{
					pause();
					start.setImageResource(R.drawable.player_paly);
				}
				isPaused = !isPaused;
			}
        	
        });
        
        
        sound.setOnClickListener(new OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			cancelDelayHide();
			if(isSoundShow){
				mSoundWindow.dismiss();
			}else{
				if(mSoundWindow.isShowing()){
					mSoundWindow.update(15,0,SoundView.MY_WIDTH,SoundView.MY_HEIGHT);
				}else{
					mSoundWindow.showAtLocation(mVideoView, Gravity.RIGHT|Gravity.CENTER_VERTICAL, 15, 0);
					mSoundWindow.update(15,0,SoundView.MY_WIDTH,SoundView.MY_HEIGHT);
				}
			}
			isSoundShow = !isSoundShow;
			hideControllerDelay();
		}   
       });
        
        sound.setOnLongClickListener(new OnLongClickListener(){
			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				if(isSilent){
					sound.setImageResource(R.drawable.soundenable);
				}else{
					sound.setImageResource(R.drawable.sounddisable);
				}
				isSilent = !isSilent;
				updateVolume(currentVolume);
				cancelDelayHide();
				hideControllerDelay();
				return true;
			}
        	
        });
        
        mSoundView = new SoundView(this);
        mSoundView.setOnVolumeChangeListener(new OnVolumeChangedListener(){

			@Override
			public void setYourVolume(int index) {
				 
				cancelDelayHide();
				updateVolume(index);
				hideControllerDelay();
			}
        });
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        
        mSoundWindow = new PopupWindow(mSoundView);
        seekBar = (SeekBar) controlView.findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
				@Override
				public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
					if(fromUser){
						if(!isOnline){
							seekTo(progress);
						}
					}
				}
	
				@Override
				public void onStartTrackingTouch(SeekBar arg0) {
					myHandler.removeMessages(HIDE_CONTROLER);
				}
	
				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					myHandler.sendEmptyMessageDelayed(HIDE_CONTROLER, TIME);
				}
        	});
        getScreenSize();
        mGestureDetector = new GestureDetector(new SimpleOnGestureListener(){

			@Override
			public boolean onDoubleTap(MotionEvent e) {
//				// TODO Auto-generated method stub
//				if(isFullScreen){
//					setVideoScale(SCREEN_DEFAULT);
//				}else{
//					setVideoScale(SCREEN_FULL);
//				}
//				isFullScreen = !isFullScreen;
//				Log.d(TAG, "onDoubleTap");
//				
//				if(isControllerShow){
//					showController();
//				}
				//return super.onDoubleTap(e);
				return true;
			}

			@Override
			public boolean onSingleTapConfirmed(MotionEvent e) {
				// TODO Auto-generated method stub
				if(!isControllerShow){
					showController();
					hideControllerDelay();
				}else {
					cancelDelayHide();
					hideController();
				}
				//return super.onSingleTapConfirmed(e);
				return true;
			}

			@Override
			public void onLongPress(MotionEvent e) {
				// TODO Auto-generated method stub
//				if(isPaused){
//					mVideoView.start();
//					start.setImageResource(R.drawable.player_pause);
//					cancelDelayHide();
//					hideControllerDelay();
//				}else{
//					mVideoView.pause();
//					start.setImageResource(R.drawable.play);
//					cancelDelayHide();
//					showController();
//				}
//				isPaused = !isPaused;
				//super.onLongPress(e);
			}	
        });
        
        holder = mVideoView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        if (getIntent() != null) {
        	path = getIntent().getStringExtra(CONSTANT.ARGS.URL);
        	mPlayedTime = getIntent().getIntExtra(CONSTANT.ARGS.POSITION, 0);
		}
    }

    private void getScreenSize(){
		Display display = getWindowManager().getDefaultDisplay();
        screenHeight = display.getHeight();
        screenWidth = display.getWidth();
        controlHeight = screenHeight/4;
	}
    
    @Override
	public boolean onTouchEvent(MotionEvent event) {
		boolean result = mGestureDetector.onTouchEvent(event);
		
		if(!result){
			if(event.getAction()==MotionEvent.ACTION_UP){
				
				/*if(!isControllerShow){
					showController();
					hideControllerDelay();
				}else {
					cancelDelayHide();
					hideController();
				}*/
			}
			result = super.onTouchEvent(event);
		}
		
		return result;
	}
    private final static int PROGRESS_CHANGED = 0;
    private final static int HIDE_CONTROLER = 1;
    
    private void updateVolume(int index){
    	if(mAudioManager!=null){
    		if(isSilent){
    			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
    		}else{
    			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
    		}
    		currentVolume = index;
    		sound.setAlpha(findAlphaFromSound());
    	}
    }
    private int findAlphaFromSound(){
    	if(mAudioManager!=null){
    		//int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    		int alpha = currentVolume * (0xCC-0x55) / maxVolume + 0x55;
    		return alpha;
    	}else{
    		return 0xCC;
    	}
    }
    Handler myHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case PROGRESS_CHANGED:
					int i = getCurrentPosition();
					seekBar.setProgress(i);
					if(isOnline){
						int j = getBufferPercentage();
						seekBar.setSecondaryProgress(j * seekBar.getMax() / 100);
					}else{
						seekBar.setSecondaryProgress(0);
					}
					i/=1000;
					int minute = i/60;
					int hour = minute/60;
					int second = i%60;
					minute %= 60;
					playedTextView.setText(String.format("%02d:%02d:%02d", hour,minute,second));
					
					sendEmptyMessageDelayed(PROGRESS_CHANGED, 100);
					break;
				case HIDE_CONTROLER:
					hideController();
					break;
			}
			super.handleMessage(msg);
		}	
    };
    
    public int getBufferPercentage() {
        if (mMediaPlayer != null) {
            return mCurrentBufferPercentage;
        }
        return 0;
    }
    
    public int getCurrentPosition() {
        if (mMediaPlayer != null && mIsPrepared) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }
    
    private void hideController(){
		if(controlerPop.isShowing()){
			controlerPop.update(0,0,0, 0);
//			extralWindow.update(0,0,screenWidth,0);
			isControllerShow = false;
		}
		if(mSoundWindow.isShowing()){
			mSoundWindow.dismiss();
			isSoundShow = false;
		}
	}
	
	private void hideControllerDelay(){
		myHandler.sendEmptyMessageDelayed(HIDE_CONTROLER, TIME);
	}
	
	private void showController(){
		controlerPop.update(0,0,screenWidth, controlHeight);
//		controler.update(0,screenHeight-mVideoView.getMeasuredHeight()-75,screenWidth,mControlerHeight);
//		controler.showAsDropDown(mVideoView, 0, 150);
//		if(isFullScreen){
//			extralWindow.update(0,0,screenWidth, 60);
//		}else{
//			extralWindow.update(0,25,screenWidth, 60);
//		}
		
		isControllerShow = true;
	}
	
	private void cancelDelayHide(){
		myHandler.removeMessages(HIDE_CONTROLER);
	}

    private void playVideo() {
        doCleanUp();
        try {
            LogUtil.d("------playVideo==" + this);
            mCurrentBufferPercentage = 0;
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setDisplay(holder);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnBufferingUpdateListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnVideoSizeChangedListener(this);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            LogUtil.d("error: " + e.getMessage(), e);
        }
    }

    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        LogUtil.d("onBufferingUpdate percent:" + percent);
        mCurrentBufferPercentage = percent;
    }

    public void onCompletion(MediaPlayer arg0) {
        LogUtil.d("onCompletion called::" + this);
    }

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        LogUtil.d("onVideoSizeChanged called::" + this);
        if (width == 0 || height == 0) {
            Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
            return;
        }
        mIsVideoSizeKnown = true;
        mVideoWidth = width;
        mVideoHeight = height;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
//            startVideoPlayback();
        }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        LogUtil.d("onPrepared called::" + this + ",played time==" + mPlayedTime);
        mIsVideoReadyToBePlayed = true;
        mIsPrepared = true;
        isFullScreen = false; 
		if(isControllerShow){
			showController();  
		}
		int i = getDuration();
		Log.d("onCompletion", ""+i);
		seekBar.setMax(i);
		i/=1000;
		int minute = i/60;
		int hour = minute/60;
		int second = i%60;
		minute %= 60;
		durationTextView.setText(String.format("%02d:%02d:%02d", hour,minute,second));
		/*controler.showAtLocation(vv, Gravity.BOTTOM, 0, 0);
		controler.update(screenWidth, controlHeight);
		myHandler.sendEmptyMessageDelayed(HIDE_CONTROLER, TIME);*/
		start();  
		seekTo(mPlayedTime);
		start.setImageResource(R.drawable.player_pause);
		hideControllerDelay();
		myHandler.sendEmptyMessage(PROGRESS_CHANGED);
		mProgressLayout.setVisibility(View.GONE);
        
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }
    
    public int getDuration() {
        if (mMediaPlayer != null && mIsPrepared) {
            if (mDuration > 0) {
                return mDuration;
            }
            mDuration = mMediaPlayer.getDuration();
            return mDuration;
        }
        mDuration = -1;
        return mDuration;
    }
    
    public void start() {
        if (mMediaPlayer != null && mIsPrepared) {
                mMediaPlayer.start();
                mStartWhenPrepared = false;
        } else {
            mStartWhenPrepared = true;
        }
    }

    public void pause() {
        if (mMediaPlayer != null && mIsPrepared) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            }
        }
        mStartWhenPrepared = false;
    }
    
    public void seekTo(int msec) {
        if (mMediaPlayer != null && mIsPrepared) {
            mMediaPlayer.seekTo(msec);
        } else {
            mSeekWhenPrepared = msec;
        }
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null && mIsPrepared) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }
    public void stopPlayback() {
        if (mMediaPlayer != null) {
        	LogUtil.d("stopPlayback::" + this);
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
        LogUtil.d("surfaceChanged called" + this);

    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        LogUtil.d("surfaceDestroyed called" + this);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        LogUtil.d("surfaceCreated called" + this);
        mProgressLayout.setVisibility(View.VISIBLE);
        playVideo();

    }

    @Override
	protected void onPause() {
		mPlayedTime = getCurrentPosition();
		LogUtil.d("onPause" + this + ",mPlayedTime==" + mPlayedTime );
		pause();
		start.setImageResource(R.drawable.player_paly);
		super.onPause();   
	}

	@Override
	protected void onResume() {
		LogUtil.d("onResume==" + this + ",mPlayedTime==" + mPlayedTime );
		if(!isChangedVideo){
			start();  
		}else{
			isChangedVideo = false;
		}
		if(isPlaying()){
			start.setImageResource(R.drawable.player_pause);
			hideControllerDelay();
		}
		Log.d("REQUEST", "NEW AD !");
		if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		
		super.onResume();
	}

    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	LogUtil.d("onDestroy::" + this + ",mPlayedTime==" + mPlayedTime );
    	if(controlerPop.isShowing()){
			controlerPop.dismiss();
		}
		if(mSoundWindow.isShowing()){
			mSoundWindow.dismiss();
		}
		myHandler.removeMessages(PROGRESS_CHANGED);
		myHandler.removeMessages(HIDE_CONTROLER);
		stopPlayback();
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsPrepared = false;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
    }

    private void startVideoPlayback() {
        Log.v(TAG, "startVideoPlayback::" + this);
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			int position = getCurrentPosition();
			EventBus.getDefault().post(new Integer(position));
			stopPlayback();
			finish();
		}
		return false;
	}
}
